package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis数据初始化监听器
 */
//@Component //意思是交给spring容器进行管理
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    //当然容器调用refresh()方法的时候,马上那个执行下面的逻辑
    //spring容器进行启动之后,并初始化完成之后马上执行下面逻辑
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("----------初始化开始-------------------");
        //1.查询MongoDB中所有的攻略
        List<Strategy> strategies = strategyService.list();
        //2.将攻略对象转化成vo对象
        for (Strategy strategy : strategies) {
            //判断vo对象是否已经存储到Redis中]
            if (strategyStatisVORedisService.isStrategyVoExists(strategy.getId())){
                continue;//跳过
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());

            //3.将vo对象存储到缓存中
            strategyStatisVORedisService.setStrategyStatisVO(vo);
        }
        System.out.println("----------初始化结束-------------------");
    }
}
